/*
Copyright (c) 2011 Sanjay Dasgupta (sanjay.dasgupta@gmail.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */
package asg;

import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.SplashScreen;
import java.awt.Toolkit;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public class Main extends JFrame {

    private Main() {
        splashScreen = SplashScreen.getSplashScreen();
        if (splashScreen != null) {
            splashGraphics = splashScreen.createGraphics();
            splashFM = splashGraphics.getFontMetrics();
            splashWidth = splashScreen.getBounds().width;
            splashHeight = splashScreen.getBounds().height;
        }
        object = this;
        setIconImage(AllIcons.favouritesIcon.getImage());
        splashProgressUpdate("Creating GUI");
        createGui();
        splashProgressUpdate("Executing \"sbaz update\"");
        sbazConnector.sbaz("update");
        try {packageManager.resetView();} catch (Throwable t) {
            JOptionPane.showMessageDialog(rootPane, t.toString(), "Exception in resetView()", JOptionPane.ERROR_MESSAGE);
        }
        setVisible(true);
        packageManager.arrangeGui();
        toFront();
    }

    private void createGui() {
        contentPane = getContentPane();
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension scrSize = tk.getScreenSize();
        setSize(guiWidth, guiHeight);
        setLocation((scrSize.width - guiWidth) / 2, (scrSize.height - guiHeight) / 2);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JTabbedPane tp = new JTabbedPane();
        contentPane.add(tp, BorderLayout.CENTER);
        tp.add("Package admin", packageManager);
        tp.add("Sbaz Console", sbazConnector);
    }

    void setMessage(String msg) {
        message = msg;
        repaint();
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        if (message == null || message.isEmpty()) {
            return;
        }
        //g.setFont(g.getFont().deriveFont(12f));
        FontMetrics fm = g.getFontMetrics();
        int sw1 = fm.stringWidth(busyLine);
        int sw2 = fm.stringWidth(message);
        int w = Math.max(sw1, sw2);
        int a = g.getFontMetrics().getAscent();
        int d = g.getFontMetrics().getDescent();
        int h = 2 * (a + d);
        g.setColor(Color.gray);
        g.drawRoundRect((getWidth() - w - 10) / 2, (getHeight() - h - (a + d) / 2 - 10) / 2, w + 10, h + 10, 5, 5);
        g.fillRoundRect((getWidth() - w - 10) / 2, (getHeight() - h - (a + d) / 2 - 10) / 2, w + 10, h + 10, 5, 5);
        g.setColor(Color.white);
        g.drawString(busyLine, (getWidth() - sw1) / 2, (getHeight()) / 2 - (a + d) / 2);
        g.drawString(message, (getWidth() - sw2) / 2, (getHeight()) / 2 + (a + d) / 2);
    }

    final void splashProgressUpdate(final String s) {
        if (splashGraphics == null) {
            return;
        }
        try {
            if (SwingUtilities.isEventDispatchThread()) {
                ++splashCount;
                splashGraphics.setComposite(AlphaComposite.Clear);
                int sw = splashFM.stringWidth(s);
                int h = splashFM.getHeight();
                int hal = splashFM.getAscent() + splashFM.getLeading();
                int h2 = h / 2;
                int w1 = (int) ((splashWidth - h) / 7f * splashCount);
                //splashGraphics.drawLine(0, 0, splashWidth, splashHeight);
                splashGraphics.setPaintMode();
                splashGraphics.setColor(Color.red);
                splashGraphics.fillRect(h2, (splashHeight - h - h2), splashWidth - h, h);
                splashGraphics.setColor(Color.green.darker());
                splashGraphics.fillRect(h2, (splashHeight - h - h2), w1, h);
                splashGraphics.setColor(Color.white);
                splashGraphics.drawRect(h2, (splashHeight - h - h2), splashWidth - h, h);
                //splashGraphics.setColor(Color.black);
                splashGraphics.drawString(s, (splashWidth - h - sw) / 2, (splashHeight - h - h2 + hal));
                splashScreen.update();
            } else {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        splashProgressUpdate(s);
                    }
                });
            }
        } catch (Throwable t) {}
    }

    public static void main(String args[]) {
        try {
            //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            //UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
            SwingUtilities.invokeLater(new Runnable(){
                public void run() {new Main();}
            });
        } catch (Throwable e) {
            e.printStackTrace();
            StringBuilder sb = new StringBuilder();
            while (e != null) {
                sb.append(e.getMessage()).append("\n");
                e = e.getCause();
            }
            JOptionPane.showMessageDialog(null, sb.toString());
        }
    }
    static Main object;
    private int guiHeight = 500, guiWidth = 550;
    Container contentPane;
    String managedDirectory = null;
    SbazConnector sbazConnector = new SbazConnector();
    PackageManager packageManager = new PackageManager();
    private String corePacks[] = new String[]{"base", "sbaz", "scala", "scala-devel", "scala-library", "scalap"};
    Set<String> corePackages = new HashSet<String>();

    {
        for (String p : corePacks) {
            corePackages.add(p);
        }
    }
    private String message = "";
    private String busyLine = "Busy !  please wait";
    private SplashScreen splashScreen = null;
    Graphics2D splashGraphics = null;
    private FontMetrics splashFM = null;
    private int splashWidth = 0, splashHeight = 0;
    private int splashCount = 0;
}
